package default_package;
import Requests.*;

import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;

public class HTTPClient {
/**
 * This is the main method of this class
 * It reads a line and sends a request to the server and waits for the server to respond.
 */
public static void main(String argv[]) throws Exception
{
	boolean running = true;
	String[] input = null;
	int port = -1;
	String host = null;
	String HTTPVersion = null;
	Socket clientSocket = null;
	PrintWriter outToServer = null;
	BufferedReader inFromServer = null;
	while(running) {
		// Reads the line
		input = InputParser.readLineAndParse();
		HTTPVersion = input[input.length - 1];
		// Checks if a new socket should be created
		if(clientSocket == null || clientSocket.isClosed()) {
			port = Integer.parseInt(input[2]);
			host = InputParser.getHost(input[1]);
			clientSocket = new Socket(host, port);
			outToServer = new PrintWriter(clientSocket.getOutputStream());
			inFromServer = new BufferedReader(new
					InputStreamReader(clientSocket.getInputStream()));
		}
		// Checks what kind of request should be created.
		HTTPRequest request;
		if(input[0].equals("HEAD"))
			request = new HEADRequest(input,outToServer, host);
		else if (input[0].equals("GET"))
			request = new GETRequest(input,outToServer, host);
		else if (input[0].equals("PUT"))
			request = new PUTRequest(input,outToServer, host);
		else if (input[0].equals("POST"))
			request = new POSTRequest(input,outToServer, host);
		else
			request = new UnknownRequest(input,outToServer, host);
		// Execute the request
		request.execute();
		
		// Prints out the answer from the server
		System.out.println("FROM Server: \n");
		String modifiedSentence;
		boolean reading = true;
		while(reading) {
			modifiedSentence = inFromServer.readLine();
			if(modifiedSentence.equals("End of Stream."))
				reading = false;
			else {
				System.out.println(modifiedSentence);
				reading = ! (modifiedSentence == null || modifiedSentence.equals("\r\n\r\n"));
			}
		}
		// Checks if the socket should be closed.
		if(HTTPVersion.equals("HTTP/1.0")) {
			outToServer.close();
			inFromServer.close();
			clientSocket.close();
			clientSocket = null;
		}
		
		}
}	

}